package org.example.java.util.concurrency.data_structure;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * ConcurrentModificationException
 * User: ZhangJuntao
 * Date: 13-11-17
 * Time: 下午12:41
 */
public class HashSetConcurrentModificationTest {
  final static Set<Integer> set = Collections.synchronizedSet(new HashSet<Integer>());

  public static void main(String... args) throws InterruptedException {
    for (int i = 0; i < 10; i++) {
      set.add(i);
    }

    new Thread() {
      @Override
      public void run() {
        Iterator<Integer> it = set.iterator();
        while (true) {
          synchronized (set) {
            System.out.println("1>>>>>>>>>");
            if (!it.hasNext()) break;
            int integer = it.next();
            System.out.println(integer);
            System.out.println("1<<<<<<<<<<");
          }
          Thread.yield();
          try {
            sleep(5);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }.start();

    new Thread() {
      @Override
      public void run() {
        try {
          sleep(20);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        Thread.yield();
        synchronized (set) {
          System.out.println("2>>>>>>>>>");
          set.clear();
          System.out.println("2<<<<<<<<<<");
        }
        System.out.println("==clear==");
      }
    }.start();
  }
}
